package posts

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeletePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeletePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePostLogic {
	return &DeletePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeletePostLogic) DeletePost(req *types.PostDeleteReq) (resp *types.Empty, err error) {
	if req.Id <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	postQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{})

	// 检查帖子是否存在
	var existPost model.CsCommunityPost
	if err = postQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).Find(&existPost).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existPost.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.PostNotFound)
	}

	// 删除帖子
	if err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
		if err = tx.Model(&model.CsCommunityPost{}).Where("id = ?", req.Id).Delete(&model.CsCommunityPost{}).Error; err != nil {
			return err
		}

		// 帖子点赞
		if err = tx.Model(&model.CsCommunityPostApprove{}).Where("post_id = ?", req.Id).Delete(&model.CsCommunityPostApprove{}).Error; err != nil {
			return err
		}

		// 删除评论
		if err = tx.Model(&model.CsCommunityPostComment{}).Where("post_id = ?", req.Id).Delete(&model.CsCommunityPostComment{}).Error; err != nil {
			return err
		}

		if err = tx.Model(&model.CsCommunityPostCommentApprove{}).Where("post_id = ?", req.Id).Delete(&model.CsCommunityPostCommentApprove{}).Error; err != nil {
			return err
		}

		// 删除实验映射
		if err = tx.Model(&model.CsCommunityPostExperimentMap{}).Where("post_id = ?", req.Id).Delete(&model.CsCommunityPostExperimentMap{}).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	// 删除相关

	return &types.Empty{}, nil
}
